<?php

/**
 * 商标管理系统 v1.0.1
 *
 * 商业运营到ubtm.cn官网进行授权使用。
 *
 * (c) cighsen02 <xiayu@959602.com>
 *
 * Create at：2025.05.01
 * Update at: 2025.07.03
*/

namespace App\Services\Auth;

use App\Models\User as UserModel;
use Exception;
use Laravel\Passport\RefreshTokenRepository;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

/**
 * 会员服务层
 */
class User extends UserService
{
    public function __construct(
        protected RefreshTokenRepository $refreshTokenRepository
    )
    {}

    /**
     * 注册用户
     *
     * @param array $data
     * @param string $role
     * @return UserModel
     */
    public function register(array $data, string $role = 'member'): UserModel
    {
        return $this->create($data, $role);
    }

    /**
     * 增加用户
     * 
     * @param array $data
     * @param string $role
     * @return UserModel
     */
    public function create(array $data, string $role = 'member'): UserModel
    {
        $user = UserModel::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);

        // 分配默认角色
        $user->assignRole($role);

        return $user;
    }

    /**
     * 登出
     *
     * @return void
     *
     * @throws Exception
     */
    public function destroy(): void
    {
        if (null === $token = Auth::user()?->token()) {
            throw new Exception('', 404);
        }

        $token->revoke();

        $this->refreshTokenRepository->revokeRefreshTokensByAccessTokenId($token->id);
    }
}
